package com.jaydenxiao.common.baserx;

import android.app.Activity;
import android.content.Context;
import android.net.ParseException;
import android.text.TextUtils;

import com.google.gson.JsonParseException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.jaydenxiao.common.R;
import com.jaydenxiao.common.baseapp.BaseApplication;
import com.jaydenxiao.common.commonutils.NetWorkUtils;
import com.jaydenxiao.common.commonutils.ToastUitl;
import com.jaydenxiao.common.commonwidget.LoadingDialog;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.disposables.Disposable;
import io.reactivex.observers.DisposableObserver;


/**
 * des:订阅封装
 */
public abstract class RxSubscriber<T> extends DisposableObserver<T> {

    private Context mContext;
    private String msg;
    private boolean showDialog = true;

    /** 是否显示浮动dialog **/
    public void showDialog() {
        this.showDialog = true;
    }
    public void hideDialog() {
        this.showDialog = true;
    }

    public  RxSubscriber(Context context, String msg, boolean showDialog) {
        this.mContext = context;
        this.msg = msg;
        this.showDialog = showDialog;
      //把当前的Disposable提供出去，这样可以用CompositeDisposable进行防止内存泄漏
        subscribe(this);
    }

    public RxSubscriber(Context context) {
        this(context, BaseApplication.getAppContext().getString(R.string.loading), true);
    }

    public  RxSubscriber(Context context, boolean showDialog) {
        this(context, BaseApplication.getAppContext().getString(R.string.loading), showDialog);
      
    }

        

    @Override
    public void onComplete() {
         //关掉对话框
        if (showDialog) LoadingDialog.cancelDialogForLoading();
    }


    @Override
    protected void onStart() {
        super.onStart();
        
        //打开对话框
        if (showDialog) {
            try {
                LoadingDialog.showDialogForLoading((Activity) mContext, msg, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onNext(T t) {

        _onNext(t);
    }

    @Override
    public void onError(Throwable e) {
        if (showDialog) LoadingDialog.cancelDialogForLoading();
        e.printStackTrace();
        //网络
        if (!NetWorkUtils.isNetConnected(BaseApplication.getAppContext())) {
           _onError(new ApiException(9999,BaseApplication.getAppContext().getString(R.string.no_net)));
            ToastUitl.showLong(BaseApplication.getAppContext().getString(R.string.no_net));
        } else if (e instanceof HttpException) {  //服务器异常
         if(!TextUtils.isEmpty(e.getMessage())) {
             ToastUitl.showLong(e.getMessage());
         }
            _onError(new ApiException(9998,e.getMessage()));
        }else if(e instanceof ApiException ){

            ApiException apiException=(ApiException) e;
            if(apiException!=null){
             if(apiException.getCode()==201){
                 //登录失效
                 if(!TextUtils.isEmpty(apiException.getDisplayMessage())){
                     ToastUitl.showLong(apiException.getDisplayMessage());
                     _onError(new ApiException(201,apiException.getDisplayMessage()));
                 }else{
                     ToastUitl.showLong("当前账号在其他地方登录");
                     _onError(new ApiException(201,"当前账号在其他地方登录"));
                 }
                 _TokenInvalid();

             } else if(apiException.getCode()==40002){
                 //token失效
                 ToastUitl.showLong(apiException.getDisplayMessage());
                 _TokenInvalid();
                 _onError(apiException);
             }else {
                 ToastUitl.showLong(apiException.getDisplayMessage());
                 _onError(apiException);
             }
            }


        } else if (e instanceof SocketTimeoutException || e instanceof ConnectException){   //服务器超时
            _onError(new ApiException(9997,BaseApplication.getAppContext().getString(R.string.time_out)));
            ToastUitl.showLong(BaseApplication.getAppContext().getString(R.string.time_out));
        }else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            _onError(new ApiException(9666,"解析错误"));
          //  ToastUitl.showLong("解析错误");
        } else {
            _onError(new ApiException(9100,"请求失败"));
            ToastUitl.showLong("请求失败");
        }
        }


    protected abstract void subscribe(Disposable d);

    protected abstract void _onNext(T t);

    /**
     * token失效，本来想着用activity做的，但是当前页面还要刷新数据，只能把 这个放出去了，
     */
    protected abstract  void _TokenInvalid();
   
    protected  void _onError(ApiException api){

    }


}
